<template>
  <div class="pdf-export" ref="pdfExportRefs" id="pdfExportRefs" v-loading="pdfExportLoading">
    <div class="basic-crf-content" v-for="(item, index) in sendPdfList" :key="index">
      <div class="basic-content">
        <span>受试者名缩写：{{ item.clinicalCase.nameSx }}</span>
        <span>受试者标识符：{{ item.clinicalCase.name }}</span>
      </div>
      <div class="crf-content" v-for="(v, i) in item.itemList" :key="i">
        <span style="font-size: 30px; margin-top: 20px">阶段名：{{ v.phaseName }}</span>
        <span
          style="width: 100%; font-size: 20px; text-align: center; color: #337cb9; margin: 20px 0"
        >
          {{ v.crfName }}
        </span>
        <VFormRender
          :form-json="JSON.parse(v.crfContent)"
          :form-data="JSON.parse(v.collectInfo)"
          :option-data="optionData"
          :ref="el => setFormRef(el, i)"
        >
        </VFormRender>
      </div>
    </div>
  </div>
</template>
<script setup>
import html2canvas from 'html2canvas';
import { jsPDF } from 'jspdf';
import VFormRender from '@/components/form-render/index.vue';
import { ref, reactive, computed, onMounted, defineEmits, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import caseloadOptions from '@/option/caseload/caseload';
import { useStore } from 'vuex';
import { useRoute, useRouter } from 'vue-router';
const route = useRoute();
const emit = defineEmits();
const routerQuery = ref({});
routerQuery.value = route.query;
const router = useRouter();
const store = useStore();

// const formJson = ref({});
const vFormRefs = ref([]);
const formData = ref({});
const optionData = ref({});

let pdfExportLoading = ref(false);
let pdfExportRefs = ref(null);

// 动态绑定 ref 到数组
const setFormRef = (el, index) => {
  if (el) {
    vFormRefs.value[index] = el;
  }
};

let sendPdfList = ref([]);
const open = list => {
  sendPdfList.value = list;
  initVForm(sendPdfList.value);
};
const pdf = async groupName => {
  try {
    pdfExportLoading.value = true; // 开始生成，显示 loading

    const element = pdfExportRefs.value;
    console.log('容器实际高度:', element.scrollHeight); // 确认高度是否为预期值（如 2000px）
    console.log('容器可见高度:', element.clientHeight); // 检查是否被父容器限制
    const canvas = await html2canvas(element, {
      scale: 2, // 提升分辨率（可尝试 3）
      useCORS: true, // 处理跨域图片
      logging: true, // 打开控制台日志（查看警告）
      scrollY: 0, // 禁用滚动偏移
      windowHeight: element.scrollHeight, // 设置渲染窗口高度
      height: element.scrollHeight, // 显式指定 Canvas 高度
      width: element.scrollWidth, // 显式指定 Canvas 宽度
      onclone: clonedDoc => {
        // 克隆 DOM 时修复样式
        const clonedElement = clonedDoc.getElementById('pdfExportRefs');
        clonedElement.style.overflow = 'visible';
        clonedElement.style.height = 'auto';
      },
    });

    const imgData = canvas.toDataURL('image/png');
    const pdf = new jsPDF({ orientation: 'portrait', unit: 'mm', format: 'a4' });
    const imgWidth = 210;
    const imgHeight = (canvas.height * imgWidth) / canvas.width;

    pdf.addImage(imgData, 'PNG', 0, 0, imgWidth, imgHeight);
    pdf.save(groupName + '.pdf');
  } catch (error) {
    console.error('生成 PDF 失败:', error);
    ElMessage.error('导出失败！');
  } finally {
    pdfExportLoading.value = false; // 无论成功/失败，关闭 loading
  }
};
const initVForm = list => {
  list.forEach((item, index) => {
    item.itemList.forEach((v, i) => {
      const formJson = JSON.parse(v.crfContent);
      if (vFormRefs.value[i]) {
        vFormRefs.value[i].setFormJson(formJson);
      }
    });
  });
};
defineExpose({
  open,
  pdf,
});
</script>
<style lang="scss" scoped>
.pdf-export {
  width: 100%;
  height: auto;
}
/* 禁用所有可能影响截图的 overflow */
// .pdf-export * {
//   overflow: visible !important;
// }
.basic-crf-content {
  width: 100%;
  height: auto;
  padding-top: 10px;
  border-top: 3px double #000;
  border-bottom: 3px double #000;
}
.basic-content {
  width: 100%;
  height: 50px;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  // border-top: 3px double #000;
  // border-bottom: 3px double #000;
}
.crf-content {
  width: 100%;
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
}
</style>